package com.reids.redission;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Service
public class RedissonServiceImpl implements RedissonService, DisposableBean,InitializingBean {

    @Autowired
    private RedissonClient redissonClient;

//    @PreDestroy
    @Override
    public void destroy() {
        redissonClient.shutdown();
        log.debug("destroy connection ...");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug("init connection ...");
    }

    @Override
    public void lockExecute1() {
        log.debug("lockExecute1 开始");
        RLock lock =  redissonClient.getLock("SIMPLE_LOCK_KEY");
        try {
            lock.lock();

            log.debug("lockExecute1 获得redisson锁,开始执行业务");

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            log.debug("lockExecute1 业务执行完,释放sedisson锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


        log.debug("lockExecute1 结束");
    }

    @Override
    public void lockExecute2() {
        log.debug("lockExecute2 开始");
        RLock lock =  redissonClient.getLock("SIMPLE_LOCK_KEY");
        try {
            lock.lock();

            log.debug("lockExecute2 获得redisson锁,开始执行业务");

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            log.debug("lockExecute2 业务执行完,释放sedisson锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        log.debug("lockExecute2 结束");
    }
}
